package com.mooc.lib_video.im

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.Handler
import android.os.IBinder
import android.util.Log
import com.google.gson.Gson
import com.mooc.lib_network.entity.ApiConst
import com.mooc.lib_video.im.callback.MsgCallBack
import com.mooc.lib_video.im.model.MsgEntity
import com.mooc.lib_video.im.model.SVGEntity
import com.mooc.lib_video.im.model.TextEntity
import okhttp3.*

class WebSocketService: Service() {

    //重连时间间隔->当连接意外断开时隔多久时间再次连接
    val delayTime = 10*1000L//间隔10s
    //接收到msg消息转发到activity->回调
    lateinit var msgCallBack:MsgCallBack
    //websocket连接状态
    var linkFlag = false
    lateinit var websocket: WebSocket
    val handler = Handler()

    //开启连接
    private fun open(){
        val request = Request.Builder().url(ApiConst.WEBSOCKETURL).build()
        websocket = OkHttpClient.Builder().build().newWebSocket(request,WebSocketListener())
    }
    //关闭连接
    private fun close(){
        if(linkFlag&&websocket!=null)
            websocket.close(0,"close")
    }

    //websocket监听
    inner class WebSocketListener : okhttp3.WebSocketListener() {

        //开启连接
        override fun onOpen(webSocket: WebSocket, response: Response) {
            super.onOpen(webSocket, response)
        }
        //接收到服务器push过来得消息
        override fun onMessage(webSocket: WebSocket, text: String) {
            super.onMessage(webSocket, text)
            Log.e("ZXY","onMessage:$text")
            if(text.equals("连接成功")){
                linkFlag = true
                return
            }
            //回调消息回activity
            if (msgCallBack == null)
                return
            //数据解析
            var msgEntity:MsgEntity = Gson().fromJson(text,MsgEntity::class.java)
            //消息类型区分->文字消息为0礼物消息为1
            if (msgEntity.type == 0){
               var textEntity : TextEntity = Gson().fromJson(text,TextEntity::class.java)
                msgCallBack.msgCall(textEntity)
            }else{
                var svgEntity:SVGEntity=Gson().fromJson(text,SVGEntity::class.java)
                msgCallBack.msgCall(svgEntity)
            }
//            msgCallBack.msgCall()
        }
        //关闭连接
        override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
            super.onClosed(webSocket, code, reason)
        }
        //连接出错
        override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
            super.onFailure(webSocket, t, response)
            Log.e("ZXY","onFailure:"+response.toString())
            //执行延时任务再次连接websocket服务器
            handler.postDelayed(object : Runnable{
                override fun run() {
                    this@WebSocketService.open()
                }
            },delayTime)
        }

    }

    override fun onCreate() {
        super.onCreate()
        //开启websocket连接
        open()
    }

    override fun onBind(intent: Intent?): IBinder? {
        return WebSocketBinder()
    }

    override fun onStartCommand(intent: Intent?,
                                flags: Int, startId: Int): Int {
        //默认不添加或使用START_NOT_STICKY->服务不粘滞
        //粘滞服务，当服务后台运行时，应用程序终止当前服务，服务会自启动一次
        return START_STICKY
    }

    //服务销毁时断开长连接
    override fun onDestroy() {
        super.onDestroy()
        close()//关闭websocket连接
    }

    inner class WebSocketBinder : Binder() {
        fun getWebSocketService():WebSocketService{
            return this@WebSocketService
        }
    }

}